package com.wedimob.slideshare.task.network;

import java.net.URL;

import org.jsoup.Connection.Response;

import com.wedimob.slideshare.Reader;
import com.wedimob.slideshare.RuntimeConfig;
import com.wedimob.slideshare.Writer;
import com.wedimob.slideshare.bo.Medium;
import com.wedimob.slideshare.source.YoutubeStrategy;
import com.wedimob.slideshare.task.PoolExecutor;
import com.wedimob.slideshare.task.ProgressObserver;
import com.wedimob.slideshare.task.Task;
import com.wedimob.slideshare.task.TaskType;
import com.wedimob.slideshare.video.VideoDownloader;
import com.wedimob.slideshare.video.VideoFormat;
import com.wedimob.slideshare.video.VideoType;

public class TaskMediumWriter extends Task<Medium, Medium> {

    public TaskMediumWriter(PoolExecutor pool, Medium picture, int timeout) {
        super(TaskType.DISK, pool, picture, 0, timeout);
    }

    @Override
    public String toString() {
        return input.getUrl().toString();
    }

    @Override
    public void run() {
        try {
            URL url = input.getUrl();
            Reader reader = RuntimeConfig.getInstance().getReader();
            Writer writer = RuntimeConfig.getInstance().getWriter();

            if (accept(url, YoutubeStrategy.URL_BASE)) {
                VideoDownloader vdown = new VideoDownloader(url);
                vdown.addObserver(new ProgressObserver(5));
                vdown.download(VideoType.MP4, VideoFormat.SMALL, input.getPath().toString());

                while (!vdown.isComplete()) {
                    Thread.sleep(100);
                }

                System.err.println("File -> " + vdown.getFile());
            } else {
                Response response = reader.getRaw(url, timeout);
                input.setExtension(response.contentType().substring(response.contentType().indexOf("/") + 1));
                writer.write(response.bodyAsBytes(), input.getFilePath());
            }
            output = input;
        } catch (Exception e) {
            e.printStackTrace();
            this.e = e;
        }
    }
}
